﻿using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace Asteroids
{
    class Background
    {

        // The image representing the parallaxing background
        Texture2D texture;

        // An array of positions of the parallaxing background
        Vector2[] positions;

        public void Initialize(ContentManager content, String texturePath, Viewport view)
        {
            // Load the background texture we will be using
            texture = content.Load<Texture2D>(texturePath);

            positions = new Vector2[4];

            // Set the initial positions of the parallaxing background
            int k = 0;
            for (int i = 0; i < positions.Length/2; i++)
            {
                for (int j = 0; j < positions.Length/2; j++, k++)
                {
                    // We need the tiles to be side by side to create a tiling effect
                    positions[k] = new Vector2(i * texture.Width, j * texture.Height);
                }
            }
        }

        public void Update(Camera camera)
        {
            Rectangle bounds = camera.screenBounds;

            for(int i = 0; i < positions.Length;i++)
            {
                if (bounds.Left < positions[i].X - texture.Width)
                {
                    positions[i].X -= 2 * texture.Width;
                }
                else if (bounds.Right > positions[i].X + 2 * texture.Width)
                {
                    positions[i].X += 2 * texture.Width;
                }

                if (bounds.Bottom > positions[i].Y + 2 * texture.Height)
                {
                    positions[i].Y += 2 * texture.Height;
                }
                else if (bounds.Top < positions[i].Y - texture.Height)
                {
                    positions[i].Y -= 2 * texture.Height;
                }

            }
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            for (int i = 0; i < positions.Length; i++)
            {
                spriteBatch.Draw(texture, positions[i], Color.White);
            }
        }
    }
}
